import {
  Form,
  Input,
  Button,
  Select,
  Upload,
  message,
  Row,
  Col,
  Space,
  Card,
  Spin,
} from 'antd';
import {
  InfoCircleOutlined,
  LoadingOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { useState, useEffect } from 'react';
import { findByDictCode, getUserInfo, saveUserAuah } from '../../../api';
import AuthExample from '../../../assets/images/auth_example.png';
import { useNavigate } from 'react-router-dom';

const Certification = () => {
  const { Option } = Select;
  const [form] = Form.useForm();
  const navigate = useNavigate();

  const [certificatesTypeList, setCertificatesTypeList] = useState([]);
  const [imageUrl, setImageUrl] = useState('');
  const [userInfo, setUserInfo] = useState({});
  const [loading, setLoading] = useState(false);

  useEffect(async () => {
    setLoading(true);
    const certificatesTypeListData = await findByDictCode('CertificatesType');
    await setCertificatesTypeList(certificatesTypeListData);
    const userInfoData = await getUserInfo();
    await setUserInfo(userInfoData);
    form.setFieldsValue(userInfoData);
    setLoading(false);
  }, []);

  const onFinish = async (values) => {
    let formData = { ...values };
    formData.certificatesUrl = imageUrl;
    await saveUserAuah(formData);
    const userInfoData = await getUserInfo();
    await setUserInfo(userInfoData);
  };

  const getCertificatesType = (id) => {
    return certificatesTypeList.find((_) => _.value == id).name;
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('你只能上传JPG/PNG文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片需小于2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const onCertificatesTypeChange = (value) => {};

  const normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };

  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      setImageUrl(info.file.response.data);
    }
  };

  if (!userInfo) {
    navigate('/');
  }

  return (
    <div className='m-l-30 m-r-30'>
      <h2>实名认证 {loading && <Spin />}</h2>

      <center>
        <p>
          <InfoCircleOutlined className='m-r-5' />
          完成实名认证后才能添加就诊人，正常进行挂号，为了不影响后续步骤，建议提前实名认证。
        </p>
      </center>

      {userInfo.authStatus === 0 && (
        <Form
          name='basic'
          labelCol={{
            span: 6,
          }}
          wrapperCol={{
            span: 12,
          }}
          form={form}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <Form.Item
            label='用户姓名'
            name='name'
            rules={[
              {
                required: true,
                message: '请输入联系人姓名全称',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name='certificatesType'
            label='证件类型：'
            rules={[
              {
                required: true,
                message: '请选择证件类型',
              },
            ]}
          >
            <Select
              placeholder='请选择证件类型'
              onChange={onCertificatesTypeChange}
              allowClear
            >
              {certificatesTypeList.map((_) => {
                return (
                  <Option value={_.value} key={_.id}>
                    {_.name}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item
            label='证件号码'
            name='certificatesNo'
            rules={[
              {
                required: true,
                message: '请输入联系人证件号码',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name='certificatesUrl'
            label='上传证件'
            valuePropName='fileList'
            getValueFromEvent={normFile}
            rules={[
              {
                required: true,
                message: '请上传联系人证件图片',
              },
            ]}
          >
            <Upload
              name='file'
              listType='picture-card'
              className='avatar-uploader'
              showUploadList={false}
              action='http://syt.atguigu.cn/api/oss/file/fileUpload?fileHost=userAuah'
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? (
                <img src={imageUrl} alt='avatar' style={{ width: '100%' }} />
              ) : (
                <img
                  src={AuthExample}
                  style={{ width: '80px', height: '80px' }}
                />
              )}
            </Upload>
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 6,
              span: 18,
            }}
          >
            <Button type='primary' htmlType='submit' size='large'>
              <span style={{ color: 'white' }}>提交</span>
            </Button>
          </Form.Item>
        </Form>
      )}

      {userInfo.authStatus !== 0 && userInfo.id && (
        <div>
          <Form form={form}>
            <Card>
              <Space direction='vertical'>
                <div>用户姓名：{userInfo.name}</div>
                <div>
                  证件类型：{getCertificatesType(userInfo.certificatesType)}
                </div>
                <div>证件号码：{userInfo.certificatesNo}</div>
              </Space>
            </Card>
          </Form>
        </div>
      )}
    </div>
  );
};

export default Certification;
